<script lang="ts">
import {defineComponent} from 'vue'
import {CommonPropsMixin} from "@/views/dashboard/CommonPropsMixin";
import fileReq from "@/api/file";
import {PathUtils} from "@/utils/PathUtils";
import APlayer, {APlayerOptions} from 'aplayer-ts'
import 'aplayer-ts/src/css/base.css'
import 'aplayer-ts/src/css/fixed.css'
import ElSelectPlus from "@/components/ElSelectPlus/index.vue";
import LyricList from "@/components/MusicPlay/LyricList.vue";
import {assTextToLyricsInfos, lrcTextToLyricsInfos} from "@/components/MusicPlay/LyricsInfo";
import {NumberUtils} from "@/utils/NumberUtils";
import {useUserStore} from "@/store/modules/user.ts";
import {ElMessageBox} from "element-plus";
import FlexAuto3 from "@/components/FlexAuto3.vue";
// 音频可视化，剔除
import MusicVudio from "@/components/MusicPlay/MusicVudio.vue";

// @ts-ignore
export default defineComponent({
  name: 'MP3COM',
  components: {MusicVudio, FlexAuto3, LyricList, ElSelectPlus},
  mixins: [CommonPropsMixin],
  watch: {
    openFile: {
      immediate: true,
      async handler(val) {
        this.lyricsInfos = []
        if (val) {
          this.selectFileName=val
          await this.$nextTick()
          const name = PathUtils.getFileNameNoExt(this.openFile)
          let lrcName = name + '.lrc'
          let assName = name + '.ass'
          let options:APlayerOptions = {
            container: this.$refs.playRef,
            volume: useUserStore().userSysConfig.music.volume,
            audio: {
              name: val,
              artist: ' ',
              url: this.getSrcWithName206(val),
            },
          }
          let lrcContent = ''
          let assContent = ''
          if(this.fileList.find(i=>i.fileName === assName)) {
            try {
              let res = await fileReq.getTextFile(PathUtils.resolve(this.baseFilePath, assName))
              assContent = res.data as string
              this.lrcFileName=PathUtils.extName(assName)
            } catch (e) {
            }
          } else  if(this.fileList.find(i=>i.fileName === lrcName)) {
            try {
              let res = await fileReq.getTextFile(PathUtils.resolve(this.baseFilePath, lrcName))
              lrcContent = res.data as string
              this.lrcFileName=PathUtils.extName(lrcName)
            } catch (e) {
            }
          }
          this.play(options,lrcContent,assContent)
        }
      }
    }
  },
  data() {
    return {
      aPlayer: null as APlayer,
      useUserStore,
      selectFileName: '',
      currentTime: 0,
      lrcFileName: '',
      lyricsInfos: [],
      playTypeOptions: [
        '顺序播放',
        '随机播放',
        '单曲循环',
      ].map(i=>{
        return {
          label: i,
          value: i,
        }
      })
    }
  },
  computed: {
    comFileList() {
      return this.fileList.filter(i=>".mp3" === PathUtils.extName(i.fileName).toLowerCase())
    },
    sliderVolume: {
      get() {
        return parseInt(useUserStore().userSysConfig.music.volume * 100 + '')
      },
      set(val) {
        useUserStore().userSysConfig.music.volume = val / 100
        if(this.aPlayer) {
          this.aPlayer.volume(useUserStore().userSysConfig.music.volume,true)
        }
      }
    }
  },
  methods: {
    play(options: APlayerOptions,lrcContent:string,assContent:string) {
      this.destroy()
      // https://github.com/liuly0322/aplayer-ts 文档
      // https://aplayer.js.org/#/zh-Hans/?id=%E4%BA%8B%E4%BB%B6%E7%BB%91%E5%AE%9A
      this.aPlayer = APlayer()
        .init(options)
      this.aPlayer.on('loadedmetadata',()=>{
        this.aPlayer.play()
        let musicLength = this.aPlayer.audio.duration * 1000
        if(assContent) {
          this.lyricsInfos = assTextToLyricsInfos(assContent,musicLength)
        } else if(lrcContent) {
          this.lyricsInfos = lrcTextToLyricsInfos(lrcContent,musicLength)
        }
      })
      this.aPlayer.on('ended',()=>{
        if(useUserStore().userSysConfig.music.playType === '顺序播放') {
          this.nextBtnClick()
        } else if(useUserStore().userSysConfig.music.playType === '随机播放') {
          while (true) {
            let name = NumberUtils.randomRightOpen(0,this.comFileList.length,0)
            name = this.comFileList[name].fileName
            if(name !== this.openFile) {
              this.openFileSetRoute(name)
              break;
            }
          }
        } else if(useUserStore().userSysConfig.music.playType === '单曲循环') {
          this.aPlayer.seek(0)
        }
      })
      this.aPlayer.on('timeupdate',()=>{
        if(this.aPlayer?.audio) {
          this.currentTime = this.aPlayer.audio.currentTime * 1000
        }
      })
    },
    playStartL(time) {
      if(this.aPlayer) {
        this.aPlayer.seek(time / 1000)
      }
    },
    destroy() {
      if(this.aPlayer) {
        this.aPlayer.destroy()
        this.aPlayer = null
      }
    },
    nowLrcEvents(lrc: string) {
      document.title = lrc
    },
    deleteItem(item){
      const name = PathUtils.getFileNameNoExt(item.label)
      let lrcName = name + '.lrc'
      let assName = name + '.ass'
      let delList = [
        PathUtils.resolve(this.baseFilePath,item.label)
      ]
      if(this.fileList.find(i=>i.fileName === assName)) {
        delList.push( PathUtils.resolve(this.baseFilePath,assName))
      }
      if(this.fileList.find(i=>i.fileName === lrcName)) {
        delList.push( PathUtils.resolve(this.baseFilePath,lrcName))
      }
      // @ts-ignore
      ElMessageBox.confirm(`${item.label}是否确认删除？`,'Warning', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(()=>{
        if(this.openFile === item.label) {
          this.nextBtnClick()
        }
        fileReq.deleteFileOrDir(delList).then(res=>{
          this.refreshFileList()
        })
      })
    }
  },
  beforeUnmount() {
    this.destroy()
  }
})
</script>

<template>
  <div class="MP3COM">
    <div>
      <div class="lime">
        <div class="name" style="width: 90px">
          音量：{{ sliderVolume }}
        </div>
        <el-slider v-model="sliderVolume"
                   :min="0"
                   :max="100"
        />
      </div>
      <div class="lime">
        <span class="name">
          歌曲：
        </span>
        <ElSelectPlus
          v-model="selectFileName"
          :options="comFileList.map(i=> {return {value: i.fileName,label: i.fileName}})"
          @change="openFileSetRoute"
          filterable
        >
          <template #default="item">
            <div class="nameItem">
              <FlexAuto3>
                <div class="single-line-ellipsis">
                  {{item.label}}
                </div>
              </FlexAuto3>
              <el-button
                text
                icon="Delete"
                type="danger"
                v-if="checkAuths(['del'])"
                @click.stop="deleteItem(item)"
              ></el-button>
            </div>
          </template>
        </ElSelectPlus>
      </div>
      <div class="lime">
        <span class="name">
          播放顺序：
        </span>
        <ElSelectPlus
          v-model="useUserStore().userSysConfig.music.playType"
          :options="playTypeOptions"
        ></ElSelectPlus>
      </div>
    </div>
    <div class="play">
      <div>
        <div ref="playRef">

        </div>
      </div>
      <div class="lrc">
        <LyricList
          v-if="lyricsInfos.length"
          :time="currentTime"
          :lyrics-infos="lyricsInfos"
          @nowLrc="nowLrcEvents"
          @play-start="playStartL"
        ></LyricList>
      </div>
      <div>
        {{lrcFileName}}
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss" src="./AUDIO_COM.scss"></style>
